# -*- coding: utf8 -*-

import os

from exception import CompileError, SPJCompileError


class Compiler(object):
  def compileSrc(self, src_file, work_dir, compile_config, is_spj=False):
      command = compile_config['command']
      exe_file = os.path.join(work_dir, compile_config['exe_name'])
      err_file = os.path.join(work_dir, 'error.log')
      command = command.format(src=src_file, exe=exe_file, err=err_file)
      compile_result = os.system(command)
      if compile_result != 0:
        # raise CompileError
        if os.path.exists(err_file):
          with open(err_file) as f:
            err_message = f.readlines()
            if err_message:
              if is_spj:
                raise SPJCompileError(err_message)
              raise CompileError(err_message)
        raise CompileError("Compiler runtime error, info: %d" %compile_result)
      return True